import { request } from '../../request/index.js'

Page({
  data: {
    wenzi: '按热度',
    fenLei: true,
    navHeight: '',
    menuButtonInfo: {},
    searchMarginTop: 0, // 搜索框上边距
    searchWidth: 0, // 搜索框宽度
    searchHeight: 0, // 搜索框高度
    news: [],
    // userId: wx.getStorageSync('userId'),
    image: [],
    guangao: false
  },
  curentPage: 1,

  onMessage(data) {
    if (getApp().globalData.wdxx > 0) {
      wx.setTabBarBadge({
        index: 3, //从左边开始第几个页面显示
        text: '' + getApp().globalData.wdxx //消息条数
      })
    } else {
      wx.removeTabBarBadge({
        index: 3
      })
    }
  },

  /*实现图片放大预览的js代码*/
  preview(event) {
    const index = event.currentTarget.dataset.index
    const { id, sb } = event.currentTarget.dataset
    if (sb == 123) {
      wx.previewImage({
        current: this.data.image[index], // 当前显示图片的http链接
        urls: this.data.image // 需要预览的图片http链接列表
      })
      return
    }
    let anew = null
    this.data.news.forEach((value) => {
      if (value.id === id) anew = value
    })
    wx.previewImage({
      current: anew.imgs[index], // 当前显示图片的http链接
      urls: anew.imgs // 需要预览的图片http链接列表
    })
  },

  change1: function () {
    this.setData({
      fenLei: true,
      wenzi: '按热度'
    })
  },
  change2: function () {
    this.setData({
      fenLei: false,
      wenzi: '按时间'
    })
  },
  change3: function () {
    this.setData({ fenLei: !this.data.fenLei }, () => {
      if (this.data.fenLei) {
        this.setData({
          wenzi: '按热度'
        })
      } else {
        this.setData({
          wenzi: '按时间'
        })
      }
    })
  },
  bianse: function () {},

  onReady() {
    // 监听消息事件
    // this.onmessage()
  },
  onShow() {
    // 设置未读消息条数
    if (getApp().globalData.wdxx > 0) {
      wx.setTabBarBadge({
        index: 3, //从左边开始第几个页面显示
        text: '' + getApp().globalData.wdxx //消息条数
      })
    } else {
      wx.removeTabBarBadge({
        index: 3
      })
    }

  },

  onPullDownRefresh() {
    this.curentPage = 1
    this.getNews(1)
  },

  onReachBottom() {
    this.curentPage += 1
    this.getNews(this.curentPage)
  },

  onLoad: function () {
    const anhao = wx.getStorageSync('tancuan')
    if (!anhao) {
      wx.hideTabBar({
        animation: false
      })
      this.setData({
        guangao: true
      })
      wx.setStorageSync('tancuan', 'haha')
    }
    // 轮播图
    this.getLunBo()

    // 获取西华大学新闻
    this.getNews(1)

    this.setData(
      {
        menuButtonInfo: wx.getMenuButtonBoundingClientRect()
      },
      () => {
        const { top, width, height, right } = this.data.menuButtonInfo
        wx.getSystemInfo({
          success: (res) => {
            const { statusBarHeight } = res
            const margin = top - statusBarHeight
            this.setData({
              navHeight: height + statusBarHeight + margin * 2,
              searchMarginTop: statusBarHeight + margin, // 状态栏 + 胶囊按钮边距
              searchHeight: height, // 与胶囊按钮同高
              searchWidth: right - width // 胶囊按钮右边坐标 - 胶囊按钮宽度 = 按钮左边可使用宽度
            })
          }
        })
      }
    )
  },

  //点赞
  handChang(e) {
    const { id } = e.currentTarget.dataset
    const { num } = this.data
    num.some((item) => {
      if (item.id === id) {
        item.isClick = !item.isClick
        return true
      }
    })
    this.setData({
      num
    })
  },

  // 对话
  zhuanfa(e) {
    const { userid } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/personal/personal?userId=${userid}`
    })
  },

  // 动态详情页
  HandXiangQiang(e) {
    const { id } = e.currentTarget.dataset
    let { news } = this.data
    let don = null
    news.some((item) => {
      if (item.id === id) {
        don = item
        return true
      }
    })
    wx.navigateTo({
      url: '/pages/news/news?new=' + encodeURIComponent(JSON.stringify(don))
    })
  },


  // 获取西华大学新闻
  async getNews(curPage) {
    const { data } = await request({
      url: `/xhuNews/${curPage}`,
      method: 'post'
    })
    if (data.state === 1) {
      let newNews = data.data
      if (newNews.length <= 0) {
        this.curentPage -= 1
        wx.showToast({
          title: '没有了呢',
          icon: 'none',
          duration: 1500
        })
        return
      }
      // new_imgs
      newNews.forEach((value) => {
        const images = value.new_imgs.split('|')
        if (!value['imgs']) value['imgs'] = []
        images.forEach((item, index) => {
          if (index < images.length - 1) {
            value['imgs'].push(item)
          }
        })
      })
      let { news } = this.data
      if (curPage === 1) news = []
      news = [...news, ...data.data]
      this.setData({
        news
      })
    }
    if (data.state === -2) {
      wx.showToast({
        title: '请求过于频繁!',
        icon: 'error',
        duration: 1500
      })
    }
    wx.stopPullDownRefresh()
  },

  //  获取轮播图
  async getLunBo() {
    const { data } = await request({
      url: '/kmgzs/banner/allBanners',
      method: 'post'
    })
    const imgs = data.data.img_url
    let imgURL = imgs.split('|')
    imgURL.forEach((item, index) => {
      if(!item.includes('https://')){
        imgURL[index] = 'https://' + item
      }
    })
    this.setData({
      image: imgURL
    })
  }
})
